﻿using HelloWorld.RobotFights;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RobotsFight.RobotImplementation
{
    public class EugeneRobot:RandomRobot
    {
        private CoordinateStorage _pastCoordinates;

        public EugeneRobot()
            :base("*",ConsoleColor.Yellow)
        {
            _pastCoordinates = new DictionaryCoordinateStorage();
                    //new MatrixCoordinateStorage(10, 10);
        }

        private void Unblock(int x, int y, Func<int, int, Robot, int> checkEmpty)
        {
            for (int step = 1; true; step++)
            {
                if (!_pastCoordinates.HasBeenAtCoordinate(x - step, y) && checkEmpty(x-step,y,this) == 0)
                {
                    //to the left
                    _pastCoordinates.FreeRobot(x, y, Direction.Left);
                    break;
                }
                if (!_pastCoordinates.HasBeenAtCoordinate(x, y - step) && checkEmpty(x, y - step, this) == 0)
                {
                    //above
                    _pastCoordinates.FreeRobot(x, y, Direction.Top);
                    break;
                }
                if (!_pastCoordinates.HasBeenAtCoordinate(x, y + step) && checkEmpty(x, y + step, this) == 0)
                {
                    //below
                    _pastCoordinates.FreeRobot(x, y, Direction.Bottom);
                    break;
                }
                if (!_pastCoordinates.HasBeenAtCoordinate(x + step, y) && checkEmpty(x + step, y, this) == 0)
                {
                    //to the right
                    _pastCoordinates.FreeRobot(x, y, Direction.Right);
                    break;
                }
            }
        }


        public override void DoStep(Func<int, int, Robot, int> checkEmpty)
        {
            if (_pastCoordinates.IsRobotBlocked(x, y,checkEmpty(x+1,y,this) != 0,checkEmpty(x,y+1,this) != 0))
            {
                Unblock(x, y, checkEmpty);
            }
            do
            {
                base.DoStep(checkEmpty);
            }
            while (_pastCoordinates.HasBeenAtCoordinate(this.x, this.y) && checkEmpty(x,y,this) == 0);

            _pastCoordinates.AddCordinate(this.x, this.y);
        }
    }
}
